<?php
	session_start();
	include_once("../../phpServices/GlobalFunction.php");
	include_once("../../phpServices/Services.php");
	$CourseAnnouncementResultDTO = new CourseAnnouncementResultDTO();
	$CourseAnnouncementResultService = new CourseAnnouncementResultService();
	
	if(!isset($_GET["CourseAnnouncementResultID"])){
		$CourseID = $_POST["hiddenCourseID"];	
		$TopicIndex = $_POST["hiddenTopicIndex"];	
		$CourseAnnouncementResultDTO->StudentCode = GetCurrentUserCode();
		$CourseAnnouncementResultDTO->CourseAnnouncementID = $_POST["ddlTopic"];
		$CourseAnnouncementResultDTO->Description = $_POST["txtDescription"];
		$CourseAnnouncementResultDTO->CreatedDate = date("Y-m-d H:i:s");
		
		if(ISSET($_FILES["File"]['name']) && $_FILES["File"]['name']!=""){		
			$FilePath = "/Resources/Files/AnnouncementResult/$CourseAnnouncementResultDTO->CourseAnnouncementID/$CourseAnnouncementResultDTO->StudentCode/";
			$upload_path = dirname(dirname(dirname($_SERVER['SCRIPT_FILENAME']))) . $FilePath;
			
			if (!file_exists($upload_path)) {
				mkdir($upload_path, 0777, true);
			}	
		
			$filename = $_FILES['File']['name'];
			$CourseAnnouncementResultDTO->FileName = $filename;
			$CourseAnnouncementResultDTO->FilePath = ".." . $FilePath;
			move_uploaded_file($_FILES['File']['tmp_name'],$upload_path . $filename);
		}
		
		$CourseAnnouncementResultService->AddCourseAnnouncementResult($CourseAnnouncementResultDTO);
	}else{
		$CourseID = $_GET["CourseID"];
		$TopicIndex = $_GET["TopicIndex"];
		$CourseAnnouncementResultID = $_GET["CourseAnnouncementResultID"];
		$CourseAnnouncementResultDTOTemp = $CourseAnnouncementResultService->GetCourseAnnouncementResultEntity($CourseAnnouncementResultID);
		$FilePath = $CourseAnnouncementResultDTOTemp->FilePath;
		$FileName = $CourseAnnouncementResultDTOTemp->FileName;
		$FilePath .= $FileName;
		
		if($FilePath!=""){
			$upload_path = dirname(dirname(dirname($_SERVER['SCRIPT_FILENAME']))) . str_replace("../","/",$FilePath);
			DeleteFile($upload_path);
			$directory = str_replace($FileName,"",$upload_path);			
			DeleteEmptyFolder($directory);
		}
		$CourseAnnouncementResultService->DeleteCourseAnnouncementResult($CourseAnnouncementResultID);		
	}
	header("Location:../index.php?page=student-sendwork.php&CourseID=$CourseID&TopicIndex=$TopicIndex");
?>